import nn


class AlexNet:
    def __init__(self):
        self.conv1 = nn.Conv2d(3, 96, kernel_size=11, stride=4)
        self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2)
        self.pool2 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.conv3 = nn.Conv2d(256, 384, kernel_size=3, padding=1)
        self.conv4 = nn.Conv2d(384, 384, kernel_size=3, padding=1)
        self.conv5 = nn.Conv2d(384, 256, kernel_size=3, padding=1)
        self.pool3 = nn.MaxPool2d(kernel_size=3, stride=2)
        self.linear1 = nn.Linear(256*6*6, 4096)
        self.linear2 = nn.Linear(4096, 4096)
        self.linear3 = nn.Linear(4096, 1000)

    def features(self, x):
        """

        :param x: [batch_size, 3, 227, 227]
        :return: 卷积池化后的特征
        """
        # in:3*227*227 out:96*55*55
        x = self.conv1(x)
        x = nn.relu(x)
        # in:96*55*55 out:96*27*27
        x = self.pool1(x)
        # in:96*27*27 out:256*27*27
        x = self.conv2(x)
        x = nn.relu(x)
        # in:256*27*27 out:256*13*13
        x = self.pool2(x)
        # in:256*13*13 out:384*13*13
        x = self.conv3(x)
        x = nn.relu(x)
        x = self.conv4(x)
        x = nn.relu(x)
        x = self.conv5(x)
        x = nn.relu(x)
        # in: 256*13*13 out: 256*6*6
        x = self.pool3(x)
        return x

    def classifier(self, x):
        # in:[batch_Size, 9216] out:[batch_size, 4096]
        x = self.linear1(x)
        x = nn.relu(x)
        # in:[batch_size, 4096] out:[batch_size,4096]
        x = self.linear2(x)
        x = nn.relu(x)
        # in:[batch_size, 4096] out:[batch_size, 1000]
        x = self.linear3(x)
        return x

    def forward(self, x):
        # x:[batch_size, 256, 6, 6]
        x = self.features(x)
        # x:[batch_size, 9216] 展开
        x = x.reshape(x.shape[0], -1)
        x = self.classifier(x)
        return x

    def __call__(self, inputs):
        return self.forward(inputs)